package com.example.peibei.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.dingtao.common.VipBuy;
import com.dingtao.common.bean.PayOrder;
import com.dingtao.common.bean.PayResult;
import com.dingtao.common.bean.VipPageData;
import com.dingtao.common.bean.Vipvip;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.OnCallback;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.BuyVipPresenter;
import com.example.peibei.service.presenter.VipPageDataPresenter;
import com.example.peibei.ui.adapter.MemberAdapter;
import com.example.peibei.ui.weight.PayStatusDialog;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MemberActivity extends WDActivity {

    //会员期限
    //1月份
    @BindView(R.id.tv_1_money_title)
    TextView tv_1_money_title;
    @BindView(R.id.tv_1_month)
    TextView tv_1_month;
    @BindView(R.id.tv_1_money_yuan)
    TextView tv_1_money_yuan;
    @BindView(R.id.tv_1_money_sheng)
    TextView tv_1_money_sheng;
    @BindView(R.id.view_line_1_month)
    View view_line_1_month;
    @BindView(R.id.layout_1_month)
    RelativeLayout layout_1_month;
    //3月份
    @BindView(R.id.tv_3_money_title)
    TextView tv_3_money_title;
    @BindView(R.id.tv_3_month)
    TextView tv_3_month;
    @BindView(R.id.tv_3_money_yuan)
    TextView tv_3_money_yuan;
    @BindView(R.id.tv_3_money_sheng)
    TextView tv_3_money_sheng;
    @BindView(R.id.view_line_3_month)
    View view_line_3_month;
    @BindView(R.id.layout_3_month)
    RelativeLayout layout_3_month;
    //1年
    @BindView(R.id.tv_year_title)
    TextView tv_year_title;
    @BindView(R.id.tv_year)
    TextView tv_year;
    @BindView(R.id.tv_year_yuan)
    TextView tv_year_yuan;
    @BindView(R.id.tv_year_sheng)
    TextView tv_year_sheng;
    @BindView(R.id.view_line_year)
    View view_line_year;
    @BindView(R.id.layout_year)
    RelativeLayout layout_year;

    @BindView(R.id.iv_pay_icon)
    ImageView iv_pay_icon;
    @BindView(R.id.tv_pay_text)
    TextView tv_pay_text;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_left)
    TextView tv_left;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.fl_vip1)
    FrameLayout fl_vip1;
    @BindView(R.id.fl_vip2)
    FrameLayout fl_vip2;
    @BindView(R.id.fl_vip3)
    FrameLayout fl_vip3;

    int monthTermType = 3; //会员期限类型 1 1月， 3 3月， 12 1年
    int payType = 0;  //支付类型 0 余额 1 微信  2 支付宝
    long vipId;

    List<Vipvip> vipvips;
    private MemberAdapter adapter;

    private SPUtils spUtils;
    private String token;
    VipPageDataPresenter vipPageDataPresenter;
    BuyVipPresenter buyVipPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_momber;
    }

    @OnClick(R.id.layout_1_month)
    public void select1Month(){
        monthTermType = 1;
        view_line_1_month.setVisibility(View.VISIBLE);
        view_line_3_month.setVisibility(View.GONE);
        view_line_year.setVisibility(View.GONE);

        if (vipvips == null || vipvips.size() < 1){
            return;
        }
        vipId = vipvips.get(0).getId();
        tv_money.setText(vipvips.get(0).getPrice().stripTrailingZeros().toPlainString());

        layout_1_month.setBackgroundResource(R.drawable.shape_c52727_radius_14);
        layout_3_month.setBackgroundResource(R.drawable.shape_483228_radius_14);
        layout_year.setBackgroundResource(R.drawable.shape_483228_radius_14);
    }

    @OnClick(R.id.layout_3_month)
    public void select3Month(){
        monthTermType = 3;
        view_line_1_month.setVisibility(View.GONE);
        view_line_3_month.setVisibility(View.VISIBLE);
        view_line_year.setVisibility(View.GONE);

        if (vipvips == null || vipvips.size() < 2){
            return;
        }
        vipId = vipvips.get(1).getId();
        tv_money.setText(vipvips.get(1).getPrice().stripTrailingZeros().toPlainString());

        layout_1_month.setBackgroundResource(R.drawable.shape_483228_radius_14);
        layout_3_month.setBackgroundResource(R.drawable.shape_c52727_radius_14);
        layout_year.setBackgroundResource(R.drawable.shape_483228_radius_14);
    }

    @OnClick(R.id.layout_year)
    public void selectYear(){
        monthTermType = 12;
        view_line_1_month.setVisibility(View.GONE);
        view_line_3_month.setVisibility(View.GONE);
        view_line_year.setVisibility(View.VISIBLE);

        if (vipvips == null || vipvips.size() < 3){
            return;
        }
        vipId = vipvips.get(2).getId();
        tv_money.setText(vipvips.get(2).getPrice().stripTrailingZeros().toPlainString());

        layout_1_month.setBackgroundResource(R.drawable.shape_483228_radius_14);
        layout_3_month.setBackgroundResource(R.drawable.shape_483228_radius_14);
        layout_year.setBackgroundResource(R.drawable.shape_c52727_radius_14);
    }

    @OnClick(R.id.btn_buy_vip)
    public void butVpi(){
        if (vipId == 0){
            return;
        }

        buyVipPresenter.reqeust("Bearer " + token,payType,vipId);

    }

    @OnClick(R.id.iv_back)
    public void back(){
        finish();
    }

    @OnClick(R.id.layout_pay)
    public void switchPayType(){
        PayStatusDialog dialog = new PayStatusDialog(this);
        dialog.create(payType,token, new OnCallback<Integer>() {
            @Override
            public void onCall(Integer result) {
                initPayUi(result);
            }
        });
    }
    //初始化支付状态ui
    private void initPayUi(int type){
        payType = type;
        if (payType == 0){
            iv_pay_icon.setImageResource(R.mipmap.qianbao_icon);
            tv_pay_text.setText("钱包支付");
        }else if (payType == 1){
            iv_pay_icon.setImageResource(R.mipmap.wechat_icon);
            tv_pay_text.setText("微信支付");
        }else if (payType == 2){
            iv_pay_icon.setImageResource(R.mipmap.ali_pay_icon);
            tv_pay_text.setText("支付宝支付");
        }
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.member_status_bar)
                .statusBarDarkFont(true)
                .hideBar(BarHide.FLAG_SHOW_BAR)
                .init();

        spUtils = new SPUtils(this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);

        adapter = new MemberAdapter();
        rv.setLayoutManager(new GridLayoutManager(this,4));
        rv.setAdapter(adapter);

        vipPageDataPresenter = new VipPageDataPresenter(new VipPageDataCall());
        vipPageDataPresenter.reqeust("Bearer " + token);

        buyVipPresenter = new BuyVipPresenter(new ButVipCall());


        tv_left.setText("<<");
        tv_right.setText(">>");
    }

    private void initVips(List<Vipvip> vipvips){
        if (vipvips.size()<3){
            fl_vip3.setVisibility(View.GONE);
        }
        Vipvip vip;
        String text;
        SpannableString sp;
        for (int i = 0; i < vipvips.size(); i++) {
            vip = vipvips.get(i);
            switch (i){
                case 0:
                    tv_1_money_title.setText(vip.getUnit());
                    tv_1_month.setText(vip.getPrice().stripTrailingZeros().toPlainString());
                    text = "￥ "+vip.getOriginPrice().stripTrailingZeros().toPlainString();
                    sp = new SpannableString(text);
                    sp.setSpan(new StrikethroughSpan(),0,text.length(),SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv_1_money_yuan.setText(sp);
                    tv_1_money_sheng.setText("立省"+vip.getOriginPrice().subtract(vip.getPrice()).stripTrailingZeros().toPlainString());

                    break;
                case 1:
                    tv_3_money_title.setText(vip.getUnit());
                    tv_3_month.setText(vip.getPrice().stripTrailingZeros().toPlainString());
                    text = "￥ "+vip.getOriginPrice().stripTrailingZeros().toPlainString();
                    sp = new SpannableString(text);
                    sp.setSpan(new StrikethroughSpan(),0,text.length(),SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv_3_money_yuan.setText(sp);
                    tv_3_money_sheng.setText("立省"+vip.getOriginPrice().subtract(vip.getPrice()).stripTrailingZeros().toPlainString());

                    tv_money.setText(vip.getPrice().stripTrailingZeros().toPlainString());
                    vipId = vip.getId();
                    break;
                case 2:
                    tv_year_title.setText(vip.getUnit());
                    tv_year.setText(vip.getPrice().stripTrailingZeros().toPlainString());
                    text = "￥ "+vip.getOriginPrice().stripTrailingZeros().toPlainString();
                    sp = new SpannableString(text);
                    sp.setSpan(new StrikethroughSpan(),0,text.length(),SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv_year_yuan.setText(sp);
                    tv_year_sheng.setText("立省"+vip.getOriginPrice().subtract(vip.getPrice()).stripTrailingZeros().toPlainString());
                    break;
            }
        }

    }

    @Override
    protected void destoryData() {

    }

    class VipPageDataCall implements DataCall<VipPageData>{

        @Override
        public void success(VipPageData data, Object... args) {
            vipvips = data.getVips();
            adapter.setNewInstance(data.getRights());
            initVips(vipvips);
        }

        @Override
        public void fail(ApiException data, Object... args) {
            data.printStackTrace();
        }
    }

    private static final int SDK_PAY_FLAG = 1;
    class ButVipCall implements DataCall<VipBuy>{

        @Override
        public void success(VipBuy data, Object... args) {
            //支付成功后逻辑，打开注释即可
            if (payType == 0) {
                if (data.getStatus().equals("0")) {
                    UIUtils.showToastSafe("您的余额不足，请充值");
                }
            } else if (payType == 2) {
                String retString = data.getRetString();
                payOrderForAlipay(retString);
            } else {
                payOrderForWx(data);
            }
        }

        @Override
        public void fail(ApiException data, Object... args) {
            data.printStackTrace();
        }
    }

    private void payOrderForAlipay(String retString) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(MemberActivity.this);
                Map<String, String> result = alipay.payV2(retString, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void payOrderForWx(VipBuy data) {
        SubmitOrderActivity.submitOrderActivity = null;
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        IWXAPI wxapi = WXAPIFactory.createWXAPI(MemberActivity.this, SubmitOrderActivity.APP_ID, true);

        // 将应用的appId注册到微信
        wxapi.registerApp(SubmitOrderActivity.APP_ID);

        PayReq req = new PayReq();
        req.appId = data.getAppId();
        req.partnerId = data.getPartnerId();
        req.prepayId = data.getPrePayId();
        req.packageValue = data.get_package();
        req.nonceStr = data.getNonceStr();
        req.timeStamp = data.getTimestamp();
//        req.extData = extData;
        req.sign = data.getSign();

        // 调起微信支付页面
        boolean result = wxapi.sendReq(req);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        UIUtils.showToastSafe("支付成功");
                        finish();
//                        showAlert(SubmitOrderActivity.this, "支付成功" + payResult);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        UIUtils.showToastSafe(payResult.getMemo());
                    }
                    break;
                }
            }
        }
    };
}
